﻿#include "mainwindow.h"
#include <QApplication>
#include "windows.h"
#include <QCoreApplication>
#include <QSettings>
#include <QDebug>
#include <QStandardPaths>
#include <QFile>
#include <windows.h>
#define REG_RUN "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run"
#pragma comment(lib,"Advapi32.lib")
#pragma comment(lib,"User32.lib")

//设置自启默认方式:shell:startup目录下添加快捷方式。
//如果定义REGEDITSET宏,将改为注册表添加
#ifdef  REGEDITSET
//设置开机自启动
//Param:    is_auto_start     true添加/false移除
//              name          注册表保存的名字   键
//            filePath        程序路径          值
//返回值:   true设置成功/false设置失败
bool setAutoStart(bool is_auto_start,QString name,QString filePath)
{
    QSettings *settings = new QSettings(REG_RUN, QSettings::NativeFormat);
    if(is_auto_start)
    {
        if(settings->value(name).toString()!=filePath.replace("/","\\")){
            settings->setValue(name,filePath.replace("/", "\\"));
            return true;
        }
    }
    else
    {
        if(settings->value(name).toString()!=""){
            settings->remove(name);
            return true;
        }
    }
    delete settings;
    return false;
}
#else
bool setAutoStart(bool is_auto_start,QString name,QString filePath){

    QString linkPath=QStandardPaths::writableLocation\
            (QStandardPaths::ApplicationsLocation).append("/Startup/").append(name).append(".lnk");

    if(is_auto_start){
        if(!QFile(linkPath).exists())
            return QFile::link(filePath,linkPath);
    }else{
        if(QFile(linkPath).exists())
            return QFile::remove(linkPath);
    }
    return false;
}
#endif

//winAPI重启系统
bool MySystemShutdownOrRestart()
{
    HANDLE hToken;
    TOKEN_PRIVILEGES tkp;
    // Get a token for this process.
    if (!OpenProcessToken(GetCurrentProcess(),TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
        return(FALSE);
    // Get the LUID for the shutdown privilege.
    LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME,
                         &tkp.Privileges[0].Luid);
    tkp.PrivilegeCount = 1;  // one privilege to set
    tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
    // Get the shutdown privilege for this process.
    AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,(PTOKEN_PRIVILEGES)NULL, 0);
    if (GetLastError() != ERROR_SUCCESS)
        return FALSE;
    // Shut down the system and force all applications to close.
    /*
if (!ExitWindowsEx(EWX_SHUTDOWN | EWX_FORCE,
SHTDN_REASON_MAJOR_OPERATINGSYSTEM |
SHTDN_REASON_MINOR_UPGRADE |
SHTDN_REASON_FLAG_PLANNED))
*/
    //restart the system
    if (!ExitWindowsEx(EWX_REBOOT | EWX_FORCE, 0))
        return FALSE;
    //shutdown or restart was successful
    return TRUE;
}
//单例
bool checkOnly()
{
    //  创建互斥量
    HANDLE m_hMutex  =  CreateMutex(NULL, FALSE,  L"121212121212" );
    //  检查错误代码
    if  (GetLastError()  ==  ERROR_ALREADY_EXISTS)  {
        //  如果已有互斥量存在则释放句柄并复位互斥量
        CloseHandle(m_hMutex);
        m_hMutex  =  NULL;
        //  程序退出
        return  false;
    }
    else
        return true;
}

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    if(!checkOnly())
        return 0;
    if(setAutoStart(true,"TmPrinter",QCoreApplication::applicationFilePath())){
//        qDebug()<<TEXT("开机自启动设置成功，即将重启。路径：")<<QCoreApplication::applicationFilePath();
        MySystemShutdownOrRestart();
    }
    MainWindow w;
//    w.hide();
    w.show();

    return a.exec();
}
